package com.itheima.sfbx.trade.handler.aliyun;

import cn.hutool.core.util.BooleanUtil;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.wap.models.AlipayTradeWapPayResponse;
import com.itheima.sfbx.framework.commons.constant.trade.TradeConstant;
import com.itheima.sfbx.framework.commons.dto.trade.TradeVO;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.trade.client.alipay.Factory;
import com.itheima.sfbx.trade.handler.WapPayHandler;
import com.itheima.sfbx.trade.pojo.Trade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName AliWapPayHandler.java
 * @Description 手机网页支付
 */
@Slf4j
@Component
public class AliWapPayHandler extends AliCommonPayHandler implements WapPayHandler {

    @Override
    public TradeVO wapTrade(TradeVO tradeVO) {
        //1、交易前置处理：检测交易单参数
        Boolean b = beforePayHandler.checkeCreateTrade(tradeVO);
        if(BooleanUtil.isFalse(b)){
            throw new RuntimeException("交易单参数异常");
        }
        //2、交易前置处理：幂等性处理
        beforePayHandler.idempotentCreateTrade(tradeVO);
        //3、获得支付宝配置文件
        Config config = aliPayConfig.config(tradeVO.getCompanyNo());
        //4、配置如果为空，抛出异常
        if(config==null){
            throw new RuntimeException("配置文件获取异常");
        }
        //5、使用配置
        Factory factory = new Factory();
        factory.setOptions(config);
        //6、调用接口
        try {
            AlipayTradeWapPayResponse pay = factory.Wap().pay(tradeVO.getMemo(), tradeVO.getTradeOrderNo().toString(), tradeVO.getTradeAmount().toString(), tradeVO.getQuitUrl(), tradeVO.getReturnUrl());
            //7、检查网关响应结果
            boolean success = ResponseChecker.success(pay);
            if(success && !EmptyUtil.isNullOrEmpty(pay.getBody())){
                tradeVO.setPlaceOrderCode(TradeConstant.ALI_SUCCESS_CODE);
                tradeVO.setPlaceOrderMsg(TradeConstant.ALI_SUCCESS_MSG);
                tradeVO.setPlaceOrderJson(pay.getBody());
                tradeVO.setTradeState(TradeConstant.TRADE_WAIT);
                Trade bean = BeanConv.toBean(tradeVO, Trade.class);
                tradeService.save(bean);
                return BeanConv.toBean(bean,TradeVO.class);
            }else{
                log.error("支付宝下单失败：{}",pay.getBody());
                throw new RuntimeException("下单失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
